//
//  ShopSectionsVC.m
//  sensen_ios
//
//  Created by pro on 16/4/23.
//  Copyright © 2016年 pro. All rights reserved.
//

#import "ShopSectionsVC.h"

// 控制器
#import "ShopVC.h" // 商城首页
#import "ShopMessageVC.h" // 消息界面
#import "ProductDetailsVC.h" // 商品详情页面
#import "ProductDetailVC.h"
#import "ProductSearchsVC.h"
// 视图
#import "CarouselView.h" // 轮播视图
#import "ShopListHeaderView.h" // 头视图
#import "ShopSortView.h" // 排序视图
#import "ShopFilterView.h" // 筛选视图

// 单元格
#import "ProductCell.h"

// 数据
#import "ProductModel.h" // 商品列表数据

@interface ShopSectionsVC () <UICollectionViewDataSource, UICollectionViewDelegate, UICollectionViewDelegateFlowLayout, UITextFieldDelegate, ShopListHeadViewDelegate, ShopSortViewDelegate, ShopFilterViewDelegate, UITableViewDelegate, UITableViewDataSource>
{
    
    NSString *_sectionName; // 一级类目名字
    NSString *_subSectionName; // 二级类目名字
    NSString *_sortName; // 排序名字
    NSString *_filterRange; // 查询区间（自己拼接10-20）
    
    
    NSMutableArray *_itemsAry; // 商品数组
    NSInteger _page; // 当前商品的页数
}
// 属性

@property (nonatomic, assign) BOOL isShowMore; // 是否右侧导航栏显示更多

// 视图
@property (nonatomic, strong) UIView *moreView; // 点击导航栏右侧...的时候展示更多

@property (nonatomic, strong) CarouselView *carouselView; // 轮播视图

@property (nonatomic, strong) UITableView *tableView; // 表视图
@property (nonatomic, strong) UIScrollView *sectionScrollView; // 分栏滑动视图
@property (nonatomic, strong) UICollectionView *collectionView; // 商品列表视图

@property (nonatomic, strong) ShopListHeaderView *headerView; // 排序和筛选视图
@property (nonatomic, strong) ShopSortView *sortView; // 综合排序视图
@property (nonatomic, strong) ShopFilterView *filterView; // 筛选视图

// 一些小的子视图要用到，设为全局
@property (nonatomic, strong) UIImageView *remindView; // 有消息时候提醒，因为关乎是否隐藏，故设为全局


@end

@implementation ShopSectionsVC

#pragma mark - 视图方法
- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.view.backgroundColor = [UIColor whiteColor];
    
    [self _createViews];
    [self createSearchBar]; // 创建搜索栏
    [self createLeftBarButtonItemWithImagename:nil]; // 创建左侧返回按钮
    [self createRightBarButtonItemsWithImagenameAry:@[@"下拉菜单按钮"]];
    
    // 刚进入，要获得一级目录的商品列表
    [self _getData];
    // 获取轮播图片
    [self _getCarouselImgs];
    
}
- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    
    // 显示标签栏
    MainTabBarController *main = (MainTabBarController *)self.tabBarController;
    [main showTabBar];
    
    // 设置导航栏颜色
    [self.navigationController.navigationBar setBackgroundImage:[UIImage imageWithColor:SS_NAVI_ORANGE_COLOR] forBarMetrics:UIBarMetricsDefault];
    
}
- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:YES];
    // 该控制器返回或者跳转的时候要删除更多视图
    _isShowMore = NO;
    [_moreView removeFromSuperview];
    _moreView = nil;
    
    if (self.view.userInteractionEnabled == NO) {
        self.view.userInteractionEnabled = YES;
    }
    
}


#pragma mark - 获得数据
#pragma mark - 获得轮播图
- (void)_getCarouselImgs {
    
    // 获得轮播图
    NSDictionary *params = @{@"position" : GET_IMG_POSITION_ID(_sectionName)};
    [BoyeHttpClient post:@"BY_Picture_getURL" apiVerson:100 params:params success:^(AFHTTPRequestOperation *operation, id result) {
        
        // 轮播图不为空
        if (![result isKindOfClass:[NSNull class]]) {
            NSMutableArray *ary = [NSMutableArray array];
            for (NSDictionary *dic in result) {
                CarouselModel *model = [[CarouselModel alloc] initContentWithDic:dic];
                
                [ary addObject:model];
            }
            
            // 设置轮播图
            _carouselView.modelAry = ary;
        }
        // 轮播图为空
        else {
            // 轮播图为空，则传入一个元素的数组，让轮播图加载默认图片
            _carouselView.modelAry = nil;
        }
        
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        // 失败
        [SVProgressHUD showErrorWithStatus:[NSString stringWithFormat:@"%@",error.domain] withDuration:2];
    }];
}
#pragma mark - 加载数据（简化版）
/**
 *  获得查询商品列表的业务参数
 *
 *  @param sectionName    一级类目的名称
 *  @param subSectionName 二级类目的名称
 *  @param sortName       排序的名称
 *  @param filterRange    筛选的区间
 */
- (NSMutableDictionary *)_getParamsWithSectionName:(NSString *)sectionName subSectionName:(NSString *)subSectionName sortName:(NSString *)sortName filterRange:(NSString *)filterRange {
    
    NSMutableDictionary *params = [[NSMutableDictionary alloc] init];
    NSNumber *firstCateID = GET_PRODUCT_CATE_ID(@"全部", sectionName);
    NSNumber *secondCateID;
    if (subSectionName != nil) {
        secondCateID = GET_PRODUCT_CATE_ID(sectionName, subSectionName); // 二级类目id
    }
    NSString *minPrice, *maxPrice; // 价格区间
    if (filterRange != nil) {
        NSArray *priceRange = [filterRange componentsSeparatedByString:@"-"];
        minPrice = [priceRange firstObject];
        maxPrice = [priceRange lastObject];
    }
    // 本方法中一级类目一定是有的
    if (filterRange == nil) { // 不包含价格区间
        if (sortName == nil ) { // 不包含排序
            if (subSectionName == nil) { // 一级目录（最基本的，不包含任何条件）
                [params setObject:firstCateID forKey:@"cate_parent"];
            } else { // 二级目录（最基本的，不包含任何条件）
                [params setObject:firstCateID forKey:@"cate_parent"];
                [params setObject:secondCateID forKey:@"cate_id"];
                
            }
        } else { // 包含排序的
            if (subSectionName == nil) { // 一级目录（包含排序的）
                [params setObject:firstCateID forKey:@"cate_parent"];
                [params setObject:sortName forKey:@"order"];
            } else { // 二级目录（包含排序的）
                [params setObject:firstCateID forKey:@"cate_parent"];
                [params setObject:secondCateID forKey:@"cate_id"];
                [params setObject:sortName forKey:@"order"];
            }
        }
    } else { // 包含价格区间的
        [params setObject:minPrice forKey:@"min_cost"];
        [params setObject:maxPrice forKey:@"max_cost"];
        if (sortName == nil ) { // 不包含排序
            if (subSectionName == nil) { // 一级目录（包含筛选的）
                [params setObject:firstCateID forKey:@"cate_parent"];
            } else { // 二级目录（包含筛选的）
                [params setObject:firstCateID forKey:@"cate_parent"];
                [params setObject:secondCateID forKey:@"cate_id"];
                
            }
        } else { // 包含排序的
            if (subSectionName == nil) { // 一级目录（包含筛选和排序的）
                [params setObject:firstCateID forKey:@"cate_parent"];
                [params setObject:sortName forKey:@"order"];
            } else { // 二级目录（包含排序和筛选的）
                [params setObject:firstCateID forKey:@"cate_parent"];
                [params setObject:secondCateID forKey:@"cate_id"];
                [params setObject:sortName forKey:@"order"];
            }
        }
    }
    
    NSLog(@"请求参数:%@", params);
    return params;
}
- (void)_getData {
    
    [self.view endEditing:YES];
    // 获得参数
    NSMutableDictionary *params = [self _getParamsWithSectionName:_sectionName subSectionName:_subSectionName sortName:_sortName filterRange:_filterRange];
    
    _page = 1; // 加载新数据了，page重置为1
    [params setObject:@(_page) forKey:@"page_no"];
    [params setObject:@(2000) forKey:@"page_size"];
    
    [SVProgressHUD showWithStatus:@"请耐心等待..."]; // 请求中
    self.view.userInteractionEnabled = NO;
    [_tableView.footer resetNoMoreData];
    
    [BoyeHttpClient post:@"BY_Product_query" apiVerson:100 params:params success:^(AFHTTPRequestOperation *operation, id result) {
        
        // 初始化数据数组
        if (_itemsAry == nil) {
            _itemsAry = [[NSMutableArray alloc] init];
        } else {
            [_itemsAry removeAllObjects];
        }
        
        if (![result[@"list"] isKindOfClass:[NSNull class]]) { // 有数据
            for (NSDictionary *dic in result[@"list"]) {
                ProductModel *model = [[ProductModel alloc] initContentWithDic:dic];
                [_itemsAry addObject:model];
            }
        }
        [_collectionView reloadData]; // 刷新表视图
        
        [self performSelector:@selector(sss) withObject:nil afterDelay:0.001];

        [SVProgressHUD dismiss];
        self.view.userInteractionEnabled = YES;
        
        if (_itemsAry.count == [result[@"count"] integerValue]) {
            [_tableView.footer noticeNoMoreData];
        }
        
        
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        [SVProgressHUD showErrorWithStatus:@"请求失败" withDuration:2];
        self.view.userInteractionEnabled = YES;
        
    }];
}
- (void)_getMoreData {
    
    NSMutableDictionary *params = [self _getParamsWithSectionName:_sectionName subSectionName:_subSectionName sortName:_sortName filterRange:_filterRange];
    
    _page += 1; // 请求更多数据，page自增1
    [params setObject:@(_page) forKey:@"page_no"];
    [params setObject:@(20) forKey:@"page_size"];
    
    [BoyeHttpClient post:@"BY_Product_query" apiVerson:100 params:params success:^(AFHTTPRequestOperation *operation, id result) {
        if (![result[@"list"] isKindOfClass:[NSNull class]]) { // 有数据
            for (NSDictionary *dic in result[@"list"]) {
                ProductModel *model = [[ProductModel alloc] initContentWithDic:dic];
                [_itemsAry addObject:model];
            }
        }
        
        [_collectionView reloadData]; // 刷新表视图
        
        [self performSelector:@selector(sss) withObject:nil afterDelay:0.001];
        
        if (_itemsAry.count == [result[@"count"] integerValue]) {
            [_tableView.footer noticeNoMoreData];
        }
        
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        [SVProgressHUD showErrorWithStatus:@"请求失败" withDuration:2];
    }];
    
    [_tableView.footer endRefreshing]; // 结束加载更多
}
- (void)sss {
    NSLog(@"推荐商品列表的高度:%lf", _collectionView.contentSize.height);
    _collectionView.height = _collectionView.contentSize.height;
    [_tableView reloadData];

}

#pragma mark - 创建视图
// 右侧按钮的样式可以自定义，由imgname控制，如果是文字则调用下面的接口
- (void)createRightBarButtonItemsWithImagenameAry:(NSArray *)imgnameAry {
    NSMutableArray *itemsAry = [[NSMutableArray alloc] init];
    for (int i = 0; i < imgnameAry.count; i ++) {
        
        UIView *customView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 30, 30)];
        customView.userInteractionEnabled = YES;
        UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(rightClick:)];
        [customView addGestureRecognizer:tap];
        
        // 图标
        UIImageView *rightButton = [[UIImageView alloc] initWithFrame:CGRectMake((customView.width - 24)/2.0, 3, 24, 24)];
        rightButton.userInteractionEnabled = YES;
        [rightButton setImage:[UIImage imageNamed:imgnameAry[i]]];
        [customView addSubview:rightButton];
        
        UIBarButtonItem *rightBarButton = [[UIBarButtonItem alloc] initWithCustomView:customView];
        [itemsAry addObject:rightBarButton];
    }
    self.navigationItem.rightBarButtonItems = itemsAry;
}
// 创建中间的搜索栏
- (void)createSearchBar {
    UIView *searchView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH - 80 * 2, 35)];
    searchView.backgroundColor = SS_NAVI_ORANGE_LIGHT_COLOR;
    searchView.layer.cornerRadius = searchView.height / 2.0;
    
    // 搜索
    UIImageView *searchImgView = [[UIImageView alloc] initWithFrame:CGRectMake(8, 8, searchView.height - 16, searchView.height - 16)];
    searchImgView.image = [UIImage imageNamed:@"商城首页_搜索"];
    [searchView addSubview:searchImgView];
    
    // 搜索栏输入框
    UIButton *searchBtn = [[UIButton alloc] initWithFrame:CGRectMake(searchImgView.right + 5, 2, searchView.width - searchView.height / 2, 31)];
    [searchBtn addTarget:self action:@selector(searchAction) forControlEvents:UIControlEventTouchUpInside];
    searchBtn.backgroundColor = [UIColor clearColor];
    [searchBtn setTitle:_sectionName forState:UIControlStateNormal];
    searchBtn.titleLabel.font = FONT(14);
    searchBtn.contentHorizontalAlignment = UIControlContentHorizontalAlignmentLeft;
    
    [searchView addSubview:searchBtn];
    
    self.navigationItem.titleView = searchView;
}


#pragma mark - 创建视图
- (void)_createViews {
    
    [self _createTapToTopView]; // 创建返回顶部的按钮
    
    // 筛选视图们
    [self _createHeaderView]; // 筛选和排序的视图
    [self _createSortView]; // 创建排序视图
    [self _createFilterViews]; // 创建筛选视图
    
    // 单元格们
    [self _createCarouselView]; // 创建轮播视图
    [self _createSectionViews]; // 创建版块分类视图
    [self _createCollectionView]; // 创建商品列表视图
    
    // 表视图
    [self _createTableView];
    
}

// 筛选和排序的视图
- (void)_createHeaderView {
    _headerView = [[ShopListHeaderView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, 35)];
    _headerView.firstViewTitle = @"排序";
    _headerView.delegate = self;
}
// 创建排序视图
- (void)_createSortView {
    _sortView = [[ShopSortView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, 120)];
    _sortView.delegate = self;
    _sortView.hidden = YES;
    _sortView.height = 0;
    
}
// 创建筛选视图
- (void)_createFilterViews {
    _filterView = [[ShopFilterView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, 90)];
    _filterView.delegate = self;
    _filterView.hidden = YES;
    _filterView.height = 0;
}

// 轮播视图
- (void)_createCarouselView {
    _carouselView = [[CarouselView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_WIDTH/2)timerDuration:3 carouselAmount:5];
}
// 版块分类视图
- (void)_createSectionViews {
    
    NSInteger count;
    NSMutableArray *imgNames;
    NSArray *titles;
    
    switch (_type) {
        case zZKShopSectionType1:
        {
            count = 6;
            _sectionName = @"水族馆";
            titles = @[@"水族箱",@"过滤设备",@"温控设备",@"照明控制",@"增氧设备",@"潜水泵",@"鱼粮鱼药",@"水族造景",@"清洁工具",@"其他附件"];
        }
            break;
        case zZKShopSectionType2:
        {
            count = 10;
            _sectionName = @"宠物馆";
            titles = @[@"宠物服饰",@"宠物窝垫",@"宠物美容",@"宠物牵引",@"宠物笼具",@"宠物食具",@"宠物玩具",@"厕所清洁",@"食品保健",@"小宠天地",];
        }
            break;
        case zZKShopSectionType3:
        {
            count = 9;
            _sectionName = @"钓具馆";
            titles = @[@"鱼竿专区",@"鱼轮专区",@"鱼线专区",@"鱼钩专区",@"浮漂专区",@"钓鱼配件",@"饵料专区",@"装备专区",@"其他用品",];
        }
            break;
        case zZKShopSectionType4:
        {
            count = 6;
            _sectionName = @"景观园艺";
            titles = @[@"过滤器",@"过滤泵",@"喷泉泵",@"UV杀菌灯",@"园艺灯具",@"园艺附件",];
        }
            break;
        case zZKShopSectionType5:
        {
            count = 5;
            _sectionName = @"运动休闲";
            titles = @[@"露营装备",@"登山装备",@"野餐用品",@"郊游用品",@"大众体育",];
        }
            break;
        case zZKShopSectionType6:
        {
            count = 6;
            _sectionName = @"家居摆件";
            titles = @[@"家居摆件",@"汽车摆件",@"家居装饰",@"工艺花瓶",@"仿真花卉",@"铁艺花架",@"流水景观"];
        }
            break;
        case zZKShopSectionType7:
        {
            count = 6;
            _sectionName = @"花卉园艺";
            titles = @[@"花果种子",@"花盆花架",@"果蔬盆",@"园艺工具",@"肥料基质"];
        }
            break;
        case zZKShopSectionType8:
        {
            count = 4;
            _sectionName = @"户外家具";
            titles = @[@"桌椅套件",@"户外摇椅",@"户外餐桌",@"休闲椅",];
        }
            break;
        default:
            break;
    }
    imgNames = [[NSMutableArray alloc] initWithCapacity:count];
    for (int i = 0; i < titles.count; i ++) {
        NSString *imgName = [NSString stringWithFormat:@"%@_%@%i", _sectionName, titles[i], i + 1];
        [imgNames addObject:imgName];
    }
    
    CGFloat x = 0;
    CGFloat y = 0;
    CGFloat width = SCREEN_WIDTH;
    CGFloat height = width / 4.0;
    
    // 总的视图
    _sectionScrollView = [[UIScrollView alloc] initWithFrame:CGRectMake(x, y, width, height)];
    _sectionScrollView.contentSize = CGSizeMake(height * titles.count, 0);
    _sectionScrollView.showsHorizontalScrollIndicator = NO;
    
    for (int i = 0; i < titles.count; i ++) {
        
        width = SCREEN_WIDTH / 4.0;
        height = width;
        x = i * width;
        y = 0;
        UIView *sectionView = [[UIView alloc] initWithFrame:CGRectMake(x, y, width, height)];
        sectionView.tag = 10 + i;
        [_sectionScrollView addSubview:sectionView];
        // 添加手势
        UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(sectionViewTap:)];
        [sectionView addGestureRecognizer:tap];
        
        width *= 0.6;
        height = width;
        x = (sectionView.width - width) / 2.0;
        y = 0;
        UIImageView *imgView = [[UIImageView alloc] initWithFrame:CGRectMake(x, y, width, height)];
        imgView.image = [UIImage imageNamed:imgNames[i]];
        [sectionView addSubview:imgView];
        
        x = 0;
        width = sectionView.width;
        height = 12;
        UILabel *titleLabel = [[UILabel alloc] initWithFrame:CGRectMake(x, y, width, height)];
        titleLabel.userInteractionEnabled = YES;
        titleLabel.font = FONT(12);
        titleLabel.text = titles[i];
        titleLabel.textColor = [UIColor darkGrayColor];
        titleLabel.textAlignment = NSTextAlignmentCenter;
        [sectionView addSubview:titleLabel];
        titleLabel.tag = 100;
        
        // 设置位置
        imgView.top = (sectionView.height - imgView.height - titleLabel.height) / 2.0;
        titleLabel.top = imgView.bottom + 5;
    }
}

// 创建放回顶部的按钮
- (void)_createTapToTopView {
    CGFloat x = SCREEN_WIDTH - 60;
    CGFloat y = SCREEN_HEIGHT - 64 - 49 - 60;
    UIView *tapToTopView = [[UIView alloc] initWithFrame:CGRectMake(x, y, 40, 40)];
    tapToTopView.backgroundColor = SS_NAVI_ORANGE_LIGHT_COLOR;
    tapToTopView.alpha = 0.5;
    tapToTopView.layer.cornerRadius = tapToTopView.width / 2;
    tapToTopView.clipsToBounds = YES;
    
    // 添加手势
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapToTop:)];
    [tapToTopView addGestureRecognizer:tap];
    
    // 添加图片
    x = (40 - 20) / 2.0;
    y  = 0;
    UIImageView *imgView = [[UIImageView alloc] initWithFrame:CGRectMake(x, y, 20, 20)];
    imgView.image = [UIImage imageNamed:@"商城首页_返回顶部"];
    [tapToTopView addSubview:imgView];
    // 添加文字
    x = 0;
    UILabel *titleLabel = [[UILabel alloc] initWithFrame:CGRectMake(x, y, tapToTopView.width, 12)];
    titleLabel.userInteractionEnabled = YES;
    titleLabel.font = FONT(8);
    titleLabel.text = @"顶部";
    titleLabel.textColor = [UIColor whiteColor];
    titleLabel.textAlignment = NSTextAlignmentCenter;
    [tapToTopView addSubview:titleLabel];
    
    // 设置位置
    imgView.top = (tapToTopView.height - imgView.height - titleLabel.height) / 2.0;
    titleLabel.top = imgView.bottom;
}

// 创建商品列表视图
- (void)_createCollectionView {
    
    UICollectionViewFlowLayout *layout = [[UICollectionViewFlowLayout alloc] init];
    layout.minimumInteritemSpacing = 3;
    layout.minimumLineSpacing = 3;
    layout.sectionInset = UIEdgeInsetsMake(3, 3, 3, 3);
    CGFloat width = (SCREEN_WIDTH - 3 * 3) / 2.0;
    CGFloat height = width + 65;
    // 设置单元格尺寸
    layout.itemSize = CGSizeMake(width, height);

    _collectionView = [[UICollectionView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, 1) collectionViewLayout:layout];
    // 设置代理和数据源方法
    _collectionView.dataSource = self;
    _collectionView.delegate = self;
    _collectionView.backgroundColor = [UIColor groupTableViewBackgroundColor];
    
    _collectionView.scrollEnabled = NO;
    
    // 注册单元格
    UINib *nib = [UINib nibWithNibName:@"ProductCell" bundle:nil];
    [_collectionView registerNib:nib forCellWithReuseIdentifier:@"ProductCell"];
    
}
// 创建表视图
- (void)_createTableView {
    
    _tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT - 64) style:UITableViewStylePlain];
    _tableView.backgroundColor = [UIColor clearColor];
    _tableView.delegate = self;
    _tableView.dataSource = self;
    [self.view addSubview:_tableView];
    
    _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    
    // 设置表头(轮播视图)
    _tableView.tableHeaderView = _carouselView;
    
    // 下拉加载更多
    MJRefreshAutoNormalFooter *footer = [MJRefreshAutoNormalFooter footerWithRefreshingTarget:self refreshingAction:@selector(_getMoreData)];
    _tableView.footer = footer;

    
}



#pragma mark - UITableViewDataSource UITableViewDelegate
// 设置组数
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 2;
}
// 设置行数
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    
    return 1;
}
// 设置单元格属性
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    if (indexPath.section == 0) {
        static NSString *sectionCell = @"sectionCell";
        UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:sectionCell];
        if (!cell) {
            cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:sectionCell];
            cell.selectionStyle = UITableViewCellSelectionStyleNone;
            
            [cell.contentView addSubview:_sectionScrollView];
            
        }
        return cell;
    }
    if (indexPath.section == 1) {
        static NSString *listCell = @"listCell";
        UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:listCell];

        if (!cell) {
            cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:listCell];
            cell.selectionStyle = UITableViewCellSelectionStyleNone;
            
            [cell.contentView addSubview:_collectionView];
            
        }
        return cell;

    }
    
    return nil;
}
// 设置单元格行高
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
   
    if (indexPath.section == 0) {
        return _sectionScrollView.height;
    } else if (indexPath.section == 1) {
        return _collectionView.height;
    }
    
    return 44;
}
// 设置组头高
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    
    if (section == 1) {
        switch (_headerView.type) {
            case typeNone:
                return 35;
                break;
            case typeSort:
                return 35 + 120;
                break;
            case typeFilter:
                return 35 + 90;
                break;
                
            default:
                break;
        }
    }
    return 0;
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
    
    if (section == 1) {
        return _headerView;
    }
    return nil;
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section {
    
    return 0;
}
// 单元格点击事件
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    
}

#pragma mark - collectionView 代理
// 定义展示的UICollectionViewCell的个数
- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView {
    return 1;
}
// 定义展示的Section的个数
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    return _itemsAry.count;
}
// 每个UICollectionView展示的内容
-(UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    ProductCell * cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"ProductCell" forIndexPath:indexPath];
    cell.model = _itemsAry[indexPath.item];
    return cell;
}

// 单元格选中事件
- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath {
    
    ProductModel *model = _itemsAry[indexPath.item];
    
    // 跳转到详情页面
    ProductDetailsVC *vc = [[ProductDetailsVC alloc] init];
    vc.pid = model.p_id;
    [self.navigationController pushViewController:vc animated:YES];
    
    // 点击进入单元格后，重置筛选的头视图
    [_headerView tapView:typeNone];
    [_tableView reloadData];
}




#pragma mark - 点击事件
- (void)rightClick:(UITapGestureRecognizer *)tap {
    
    if (_moreView == nil) {
        _moreView = [[UIView alloc] initWithFrame:CGRectMake(SCREEN_WIDTH - 100, 60, 100, 60)];
        _moreView.backgroundColor = [UIColor whiteColor];
        [_APP_KEYWINDOW addSubview:_moreView];
        _moreView.left = SCREEN_WIDTH;
        
        // 商城首页，消息
        NSArray *titles = @[@"商城首页",@"消息"];
        NSArray *imgNames = @[@"下拉菜单回到商城首页",@"下拉菜单消息"];
        for (int i = 0; i < titles.count; i ++) {
            // 总视图，用于点击
            UIView *bgView = [[UIView alloc] initWithFrame:CGRectMake(0, i * _moreView.height / 2.0, _moreView.width, _moreView.height / 2.0)];
            bgView.tag = i + 1;
            [_moreView addSubview:bgView];
            // 添加点击手势
            UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(naviRightTap:)];
            [bgView addGestureRecognizer:tap];
            // 图片
            UIImageView *imgView = [[UIImageView alloc] initWithFrame:CGRectMake(5, 5, 20, 20)];
            imgView.image = [UIImage imageNamed:imgNames[i]];
            [bgView addSubview:imgView];
            // 文字
            UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(imgView.right + 5, imgView.top, _moreView.width - imgView.width - 10, imgView.height)];
            label.userInteractionEnabled = YES;
            label.font = FONT(14);
            label.text = titles[i];
            label.textColor = [UIColor darkGrayColor];
            label.textAlignment = NSTextAlignmentLeft;
            [bgView addSubview:label];
        }
        
    }
    
    if (!_isShowMore) {
        [UIView animateWithDuration:0.3 animations:^{
            _moreView.left = SCREEN_WIDTH - _moreView.width;
        }];
    } else {
        [UIView animateWithDuration:0.3 animations:^{
            _moreView.left = SCREEN_WIDTH;
        }];
    }
    
    // 转换是否显示
    _isShowMore = !_isShowMore;
}
// 进入搜索页面
- (void)searchAction {
    [_APP_KEYWINDOW endEditing:YES];
    ProductSearchsVC *vc = [[ProductSearchsVC alloc] init];
    [self.navigationController pushViewController:vc animated:YES];
}
// 分栏模块点击
- (void)sectionViewTap:(UITapGestureRecognizer *)tap {
    
    // 重置头视图，排序视图和筛选视图
    _sortName = nil;
    _filterRange = nil;
    [_sortView resetSortView];
    
    // 刷新商品
    UIView *sectionView = tap.view;
    UILabel *titleLabel = (UILabel *)[sectionView viewWithTag:100];
    
    // 设置二级目录的名称，用于查询
    _subSectionName = titleLabel.text;
    // 查询二级目录数据
    [self _getData];
    
    
    
}
// 点击滑动到顶部
- (void)tapToTop:(UITapGestureRecognizer *)tap {
    
    
}
// 右侧导航栏按钮点击
- (void)naviRightTap:(UITapGestureRecognizer *)tap {
    if (tap.view.tag == 1) {
        // 点击商城首页
        for (UIViewController *vc in self.navigationController.viewControllers) {
            // 找到首页，并返回到首页
            if ([vc isKindOfClass:[ShopVC class]]) {
                [self.navigationController popToViewController:vc animated:YES];
                return;
            }
        }
    } else {
        // 点击消息
        ShopMessageVC *vc = [[ShopMessageVC alloc] init];
        [self.navigationController pushViewController:vc animated:YES];
    }
}
#pragma mark - 排序，筛选视图等点击
- (void)headerViewDidSelected:(NSInteger)tag {

    [_headerView endEditing:YES];
    
        if (tag == 1) {
            [_headerView tapView:typeSort];
            [_tableView reloadData];
        }
        // 销量优先
        else if (tag == 2) {
            
            _headerView.firstViewTitle = @"排序";
            _headerView.secondTitleUse = YES;
            _sortName = @"11";

            [_headerView tapView:typeNone];
            [_tableView reloadData];
            
            // 请求排序后的参数
            [self _getData];
            
        }
        // 筛选
        else {
            [_headerView tapView:typeFilter];
            [_tableView reloadData];
        }
}
- (void)headerSortViewDidChoose:(NSInteger)tag {
    
    NSString *sortText = nil;
    switch (tag) {
        case 1:
        {
            sortText = @"综合排序";
            _sortName = @"10";
        }
            break;
        case 2:
        {
            sortText = @"价格从低到高";
            _sortName = @"12";
        }
            break;
        case 3:
        {
            sortText = @"价格从高到低";
            _sortName = @"13";
        }
            break;
        default:
            break;
    }
    
    _headerView.firstViewTitle = sortText;
    [_headerView tapView:typeNone];
    [_tableView reloadData];
    
    // 查询排序后的商品列表
    [self _getData];
}
- (void)headerFilterViewDidChooseRange:(NSString *)range {
    _filterRange = range;
    [_headerView tapView:typeNone];
    [_tableView reloadData];

    // 查询排序后的商品列表
    [self _getData];
}


#pragma mark -
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
}
@end
